//
//  ARMineRecommendationController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/23.
//

import UIKit
import SnapKit

class ARMineRecommendationController: ARBaseViewController {

    private static let cellReuseId = "ar.mineRecommendationvc.cellReuseId"
    let viewModel: ARMineRecommendationViewModel = ARMineRecommendationViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        loadData()
    }
    
    private func setupUI() {
        
        self.ar_setupNavBgImg()
        self.ar_configWhiteBackItem()
        self.title = ARHelper.localString("My Recommendation")
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: ARHelper.font(18, weight: .medium)]
        }
        
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.bottom.equalToSuperview()
        }
        
        self.view.addSubview(emptyImgView)
        self.view.addSubview(emptyLabel)
        emptyImgView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(ARHelper.heightScale(127.0))
        }
        emptyLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.top.equalTo(emptyImgView.snp.bottom).offset(16)
        }
    }
    
    private func refreshUI() {
        tableView.reloadData()
        if viewModel.dataSource.isEmpty {
            emptyLabel.isHidden = false
            emptyImgView.isHidden = false
            tableView.isHidden = true
        } else {
            emptyLabel.isHidden = true
            emptyImgView.isHidden = true
            tableView.isHidden = false
        }
    }
    
    @objc func loadData() {
        if self.refreshHeader.isRefreshing == false {
            self.ar.showLoading()
        }

        viewModel.loadData { [weak self] err in
            self?.ar.hideHUD()
            self?.refreshHeader.endRefreshing()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            self?.refreshUI()
        }
    }
    
    private lazy var tableView: UITableView = {
        var tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = .clear
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = true
        tableView.register(ARMineRecommendationCell.self, forCellReuseIdentifier: Self.cellReuseId)
        tableView.estimatedRowHeight = 295+16
        tableView.mj_header = self.refreshHeader
        
        tableView.contentInset = .init(top: 16, left: 0, bottom: ARHelper.safeBottomHeight(), right: 0)
        
        return tableView
    }()
    
    private lazy var refreshHeader: ARRefreshHeader = {
        let header = ARRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadData))
        header.stateLabel?.isHidden = true
        header.lastUpdatedTimeLabel?.isHidden = true
        return header
    }()
    
    private lazy var emptyImgView: UIImageView = {
        let view = UIImageView(image: .init(named: "mine_recommendation_empty"))
        return view
    }()
    
    private lazy var emptyLabel: UILabel = {
        let label = UILabel()
        label.font = ARHelper.font(16, weight: .regular)
        label.textColor = UIColor(hexString: "#000000")?.withAlphaComponent(0.5)
        label.text = ARHelper.localString("Share your recommendations")
        label.textAlignment = .center
        return label
    }()
    
}

extension ARMineRecommendationController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 不会经常变动，这里就不做判断
        let model = self.viewModel.dataSource[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: Self.cellReuseId, for: indexPath) as! ARMineRecommendationCell
        cell.selectionStyle = .none
        cell.updateValue(model)
        cell.operationCallback = { [weak self] aCell in
            self?.ar.showLoading()
            self?.viewModel.deleteWork(model, completion: { err in
                self?.ar.hideHUD()
                if let err = err {
                    self?.ar.makeToast(err.localizedDescription)
                    return
                }
                // 刷新
                self?.refreshUI()
            })
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 295+16
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let model = self.viewModel.dataSource[indexPath.row]
//        let vc = ARIndexWorkDetailController(workId: model.id)
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}
